/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.sgf.api.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.inspur.edp.sgf.api.extension.ObjectMapperDateFormatExtend;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 功能描述:
 *
 * @ClassName: ObjectMapperUtil
 * @Author: Fynn Qi
 * @Date: 2020/7/14 15:50
 * @Version: V1.0
 */
public class ObjectMapperUtil {

    private static final ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        setConfig(mapper);
        mapper.setConfig(mapper.getDeserializationConfig().with(new ObjectMapperDateFormatExtend()));
        mapper.registerModule(new JavaTimeModule());

        //保留BigDecimal精度
        mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
        JsonNodeFactory jsonNodeFactory = JsonNodeFactory.withExactBigDecimals(true);
        mapper.setNodeFactory(jsonNodeFactory);
    }

    public static ObjectMapper getMapper() {
        return mapper;
    }

    public static JsonParser getJsonParser(String jsonStr) {
        JsonFactory factory = new JsonFactory();
        try {
            return factory.createParser(jsonStr);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static JavaType getJavaType(Type t) {
        return mapper.constructType(t);
    }

    public static JavaType getJavaType(Class<?> collectionClazz, Class<?>... elementClazzes) {
        return mapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);
    }

    public static JsonNode jsonStrToJsonNode(String json) {
        try {
            return mapper.readTree(json);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T jsonStrToClass(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T jsonNodeToClass(JsonNode jsonNode, Class<T> clazz) {
        try {
            return mapper.treeToValue(jsonNode, clazz);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> String serialize(T obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T deserialize(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T deserialize(String content, Type type) {
        JavaType javaType = mapper.constructType(type);
        try {
            return mapper.readValue(content, javaType);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T deserialize(String content, JavaType javaType) {
        try {
            return mapper.readValue(content, javaType);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T deserialize(String content, TypeReference<T> valueTypeRef) {
        try {
            return mapper.readValue(content, valueTypeRef);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T deserialize(JsonParser p, JavaType valueType) {
        try {
            return mapper.readValue(p, valueType);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T deserialize(JsonNode node, Class<?> classz) {
        if (node == null) {
            return null;
        }
        try {
            return (T) mapper.treeToValue(node, classz);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static <T> T deserialize(
            String json, Class<?> collectionClazz, Class<?>... elementClazzs) {
        return string2Obj(json, collectionClazz, elementClazzs);
    }

    private static <T> T string2Obj(String str, Class<?> collectionClazz, Class<?>... elementClazzs) {
        JavaType javaType = getJavaType(collectionClazz, elementClazzs);
        try {
            return mapper.readValue(str, javaType);
        } catch (Exception e) {
            throw new EApiSerializeException(e);
        }
    }

    public static JsonParser getJsonParser(JsonNode node) throws IOException {
        String nodeJsonStr = ObjectMapperUtil.getMapper().writeValueAsString(node);
        JsonFactory factory = new JsonFactory();
        return factory.createParser(nodeJsonStr);
    }

    public static JsonNode valueToTree(Object fromValue) {
        return mapper.valueToTree(fromValue);
    }

    private static void setConfig(ObjectMapper om) {
        // 对象的所有字段全部列入
        om.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // 取消默认转换timestamps形式
        om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // 忽略空Bean转json的错误
        om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 忽略 在json字符串中存在，但是在java对象中不存在对应属性的情况。防止错误
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 设置可用单引号
        om.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        // 设置字段可以不用双引号包括
        om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        om.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        om.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
        // 允许缺少数据
        om.configure(JsonParser.Feature.ALLOW_MISSING_VALUES, true);
        // 大小写脱敏 默认为false  需要改为true
        om.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    }
}
